# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine 
@File    ：auth
@IDE     ：PyCharm 
@Author  ：Tony
@Date    ：2025/2/20 15:12 
@Des     ：
"""
from typing import Annotated

from fastapi import APIRouter, Depends, Request, Response, BackgroundTasks
from fastapi.security import HTTPBasicCredentials
from fastapi_limiter.depends import RateLimiter

from App.app.admin.schemas.sys_user_schema import AuthSchemaBase, GetSysUseInfoNoRoleDetail
from App.app.admin.schemas.token import GetSwaggerToken, ReqRefreshToken
from App.app.admin.services.auth_service import AuthService
from App.common.respones.response_schema import response_base, ResponseModel
from App.config.log_conf import log

router = APIRouter()


@router.post('/login/swagger', summary='swagger 调试专用，前端无需理会', description='用于快捷登录进行swagger调试')
async def swagger_login(obj_in: Annotated[HTTPBasicCredentials, Depends()]) -> GetSwaggerToken:
    token, user = await AuthService.swagger_login(obj_in=obj_in)
    return GetSwaggerToken(access_token=token, user=GetSysUseInfoNoRoleDetail.model_validate(user))


@router.post(
    '/login',
    summary='用户登录',
    description='用户登录接口',
    dependencies=[Depends(RateLimiter(times=20, minutes=1))]
)
async def user_login(
    request: Request, response: Response, obj_in: AuthSchemaBase, background_tasks: BackgroundTasks
) -> ResponseModel:
    data = await AuthService.login(request=request, response=response, obj_in=obj_in, background_tasks=background_tasks)
    return response_base.success(data=data)


@router.post('/token/refresh', summary='刷新token')
async def refresh_token(request: Request, response: Response, req: ReqRefreshToken) -> ResponseModel:
    data = await AuthService.refresh_token(request=request, refresh_token=req.refresh_token)
    return response_base.success(data=data)


@router.post('/logout', summary='用户登出', dependencies=[Depends(RateLimiter(times=20, minutes=1))])
async def user_logout(request: Request, response: Response) -> ResponseModel:
    try:
        await AuthService.logout(request=request, response=response)
    except Exception as e:
        log.error(e)
    finally:
        return response_base.success()
